<%@ page session="true"%>
<%@ page import="java.util.Map,java.util.Iterator,org.openid4java.discovery.Identifier,org.openid4java.discovery.DiscoveryInformation,org.openid4java.message.ax.FetchRequest,org.openid4java.message.ax.FetchResponse,org.openid4java.message.ax.AxMessage,org.openid4java.message.*,org.openid4java.OpenIDException,java.util.List,java.io.IOException,javax.servlet.http.HttpSession,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,org.openid4java.consumer.ConsumerManager,org.openid4java.consumer.InMemoryConsumerAssociationStore,org.openid4java.consumer.InMemoryNonceVerifier"%>
<%@ page import="org.openid4java.OpenIDException"%>
<%@ page import="org.openid4java.util.*"%>
<%@ page import="org.openid4java.consumer.*" %>
<%@ page import="org.openid4java.message.sreg.*" %>
<%

//String returnToUrl = "http://deskpro14578.dynamic.sanger.ac.uk:8080/writebackServlet/consumer_returnurl.jsp";
String returnToUrl = "http://localhost:8088/writebackServlet/consumer_returnurl.jsp";

System.out.print("got returnToURL: " + returnToUrl);

/*
Cookie[] cookies = request.getCookies();

for (int i=0; i< cookies.length; i++) {
	Cookie c = cookies[i];
	if ( c.getName().equals("JSESSIONID")){
		returnToUrl += "?JSESSIONID=" + c.getValue();
		break;
	}
}
*/
System.out.println("consumer_returnurl:" + returnToUrl);


%>

<% 
	String openid   = request.getParameter("openid");
	String remember = request.getParameter("remember"); 
	
	if (( remember != null ) && (remember.equals("1"))){
		// set cookie with openid name
		
	       Cookie mycookie = new Cookie("claimedOpenIDName",openid);
	       response.addCookie(mycookie);
	 
	} else {
		   Cookie mycookie = new Cookie("claimedOpenIDName","");
	       response.addCookie(mycookie);	       
	 
	}
%>


<%
	// README:
	// Set the returnToUrl string to the appropriate value for this JSP
	// Since you may be deployed behind apache, etc, the jsp has no real idea what the
	// absolute URI is to get back here.

	//  --- Forward proxy setup (only if needed) ---
	//== Asja commented ==
	//ProxyProperties proxyProps = new ProxyProperties();
	//proxyProps.setProxyHostName("wwwcache.sanger.ac.uk");
	//proxyProps.setProxyPort(3128);
	//HttpClientFactory.setProxyProperties(proxyProps);

	
	
	
	Object o = pageContext.getAttribute("consumermanager",
		pageContext.APPLICATION_SCOPE);
	if (o == null) {
		ConsumerManager newmgr = new ConsumerManager();
		newmgr.setAssociations(new InMemoryConsumerAssociationStore());
		newmgr.setNonceVerifier(new InMemoryNonceVerifier(5000));
		pageContext.setAttribute("consumermanager", newmgr,
		pageContext.APPLICATION_SCOPE);
	}
	ConsumerManager manager = (ConsumerManager) pageContext.getAttribute(
			"consumermanager",
			pageContext.APPLICATION_SCOPE);




	try {
		// determine a return_to URL where your application will receive
		// the authentication responses from the OpenID provider
		// YOU SHOULD CHANGE THIS TO GO TO THE

		// perform discovery on the user-supplied identifier
		List discoveries = manager.discover(openid);

		// attempt to associate with an OpenID provider
		// and retrieve one service endpoint for authentication
		DiscoveryInformation discovered = manager
		.associate(discoveries);

		// store the discovery information in the user's session
		session.setAttribute("openid-disco", discovered);
		//System.out.println("discovered: " + discovered);
		// obtain a AuthRequest message to be sent to the OpenID provider
		
		SRegRequest sregReq = SRegRequest.createFetchRequest();

		//sregReq.addAttribute("fullname", true);
		//sregReq.addAttribute("nickname", true);
		sregReq.addAttribute("email", true);

		AuthRequest authReq = manager.authenticate(discovered,returnToUrl);
		authReq.addExtension(sregReq);
      
		
		// Attribute Exchange example: fetching the 'email' attribute
		///*
		//FetchRequest fetch = FetchRequest.createFetchRequest();
		//fetch.addAttribute("email",
		// attribute alias
		//       "http://schema.openid.net/contact/email",   // type URI
		//       true);                                      // required

		// attach the extension to the authentication request
		//authReq.addExtension(fetch);
		//*/
		if (!discovered.isVersion2()) {
	// Option 1: GET HTTP-redirect to the OpenID Provider endpoint
	// The only method supported in OpenID 1.x
	// redirect-URL usually limited ~2048 bytes
		String authUrl = authReq.getDestinationUrl(true);
		response.sendRedirect(authUrl);
	
	// email hack from openid4java mailing list:
		//System.out.println("adding email yo openID request");
			//String authUrl = authReq.getDestinationUrl(true);
			//authUrl = authUrl + "&openid.sreg.required=email";
            //authUrl = authUrl + "&openid.sreg.required=email%2Cnickname";
            //response.sendRedirect(authUrl);
            return ; 
	
	
		} else {
	// Option 2: HTML FORM Redirection
	// Allows payloads > 2048 bytes

	// <FORM action="OpenID Provider's service endpoint">
	// see samples/formredirection.jsp for a JSP example
	//authReq.getOPEndpoint();

	// build a HTML FORM with the message parameters
	//authReq.getParameterMap();
%>


<html>
<head>
<title>OpenID HTML FORM Redirection</title>
</head>
<body onload="document.forms['openid-form-redirection'].submit();">
<body>
<p>You will be automatically redicted to <a
	href="http://www.myopenid.com">http://www.myopenid.com</a>, in order to
authenticate your login.</p>
<p>If the redirect fails please press the Continue button.</p>


<form name="openid-form-redirection"
	action="<%= authReq.getOPEndpoint() %>" method="post"
	accept-charset="utf-8">
<%
	Map pm = authReq.getParameterMap();
	Iterator keyit = pm.keySet().iterator();

	Object key;
	Object value;

	while (keyit.hasNext()) {
		key = keyit.next();
		value = pm.get(key);
		
		
		System.out.println(key + " " + value);
%> <input type="hidden" name="<%= key%>" value="<%= value%>" /> 
<%
 }
	
 %>
 <input type="hidden" name="openid.sreg.required" value="email"/>
<button type="submit">Continue...</button>
</form>
</body>
</html>
<%
	}
	} catch (OpenIDException e) {
		e.printStackTrace();
		// present error to the user
		//response.sendError(500);
		session.setAttribute("message", e.getMessage());
		String newUrl = "login.jsp";
		response.sendRedirect(newUrl);

	}
%>
